package com.common.fileuse.PicUrlToStream;


import org.apache.poi.util.IOUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Base64;

/**
 * @author klay
 * @date 2021/9/27
 */
public class TestBase64 {

    public static void main(String[] args) {
        //可正常访问的url地址
        String url = "https://172.16.30.10:443/ngx/proxy?i=aHR0cDovLzE3Mi4xNi4zMC4xMDo2MTIwL3BpYz8wZDlkNjc0Y2YyNGRvLTdlbCozMS1mMTlvZj0zMTIzKjNsNT0wNjAwKjAyMDk0Mzc9NzE5NCpwdD09MjE4KioyczcqNGIxPTk5YmUzMTA1MGQ1NTU4LTkxODZvZC0ycGk3YWNkPTE5PTc5Zg==";
        String base64 = getBase64(url);
        System.out.println("生成Base64：" + base64);
    }

    public static String getBase64(String url) {
        String result = "";
        //转成Base64
        InputStream httpsFile = null;
        try {
            httpsFile = getHttpsFile(url);
            byte[] bytes = IOUtils.toByteArray(httpsFile);
            result = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static InputStream getHttpsFile(String fileUrl) throws NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyManagementException {
        // 创建SSLContext对象，使用指定的信任管理器初始化
        if (fileUrl.contains("https:")) {//https
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(fileUrl);
            HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
            httpsConn.setSSLSocketFactory(ssf);
            httpsConn.setDoInput(true);
            httpsConn.setDoOutput(true);
            return httpsConn.getInputStream();
        } else {//http
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10 * 1000);
            return connection.getInputStream();
        }
    }

}